package com.blood.core.util.http;

import javax.servlet.http.HttpServletRequest;

/**
 * @Description
 * @Author yelong
 * @CreateDate 2020-06-04 12:40
 */
public class HttpRequestUtils {

    // 通过请求对象，获取客户端的ip地址
    public static String getRemoteAddress(HttpServletRequest request) {
        if (request == null) {
            return "";
        }

        String ip = request.getHeader("X-Forwarded-For");

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("Proxy-Client-IP");
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("WL-Proxy-Client-IP");
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_CLIENT_IP");
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTP_X_FORWARDED_FOR");
            }
            if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
                ip = request.getRemoteAddr();
            }
        } else if (ip.length() > 15) {
            String[] ips = ip.split(",");
            for (int index = 0; index < ips.length; index++) {
                String strIp = (String) ips[index];
                if (!("unknown".equalsIgnoreCase(strIp))) {
                    ip = strIp;
                    break;
                }
            }
        }

        if (ip == null) {
            return "";
        }

        return ip;
    }

    // 通过请求对象，获取访问路径
    private static String getRequestURI(HttpServletRequest request, boolean includeContextPath) {
        String requestURI = request.getRequestURI();
        if (includeContextPath) {
            return requestURI;
        } else {
            String contextPath = request.getContextPath();
            return requestURI.replace(contextPath, "");
        }
    }

    public static String getRequestURI(HttpServletRequest request) {
        return getRequestURI(request, false);
    }

    public static String getFullRequestURI(HttpServletRequest request) {
        return getRequestURI(request, true);
    }
}
